<template>
  <div class="settlement-page">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="text-base font-medium">结算单</div>
          <div class="space-x-2">
            <el-button
              type="primary"
              :icon="useRenderIcon('ep:plus')"
              @click="openGenerateDialog"
            >
              生成结算单
            </el-button>
            <el-button
              :icon="useRenderIcon('ep:refresh')"
              :loading="loading"
              @click="onSearch"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :inline="true"
        :model="filterForm"
        class="search-form bg-bg_color w-full pl-4 pt-3 pb-2 overflow-auto"
      >
        <el-form-item label="结算单号/备注" prop="keyword">
          <el-input
            v-model.trim="filterForm.keyword"
            placeholder="输入编号或备注关键字"
            clearable
            class="w-[220px]!"
          />
        </el-form-item>

        <el-form-item label="卖家组织" prop="seller_org_id">
          <el-select
            v-model="filterForm.seller_org_id"
            clearable
            filterable
            remote
            reserve-keyword
            placeholder="全部组织"
            :remote-method="loadSellerOrgOptions"
            :loading="orgLoading"
            class="w-[260px]!"
          >
            <el-option
              v-for="item in sellerOrgOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="filterForm.status"
            placeholder="全部状态"
            clearable
            class="w-[160px]!"
          >
            <el-option label="全部状态" value="" />
            <el-option
              v-for="item in STATEMENT_STATUS_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="结算周期" prop="period_range">
          <el-date-picker
            v-model="filterForm.period_range"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="w-[280px]!"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri:search-line')"
            :loading="loading"
            @click="onSearch"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon('ep:refresh')" @click="resetFilters">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <PureTableBar
        title="结算单列表"
        :columns="columns"
        :tableRef="tableRef"
        @refresh="onSearch"
        @fullscreen="tableRef.value?.setAdaptive?.()"
      >
        <template #default="{ size, dynamicColumns }">
          <template v-if="loading && tableData.length === 0">
            <el-skeleton :rows="10" animated />
          </template>
          <PureTable
            v-else
            ref="tableRef"
            v-loading="loading"
            row-key="id"
            :columns="dynamicColumns"
            :data="tableData"
            :size="size"
            :pagination="pagination"
            adaptive
            :adaptiveConfig="{ offsetBottom: 48 }"
            @page-current-change="handlePageChange"
            @page-size-change="handleSizeChange"
          >
            <template #status="{ row }">
              <el-tag
                :type="statusTagType(row.status)"
                effect="plain"
                size="small"
              >
                {{ row.status_label }}
              </el-tag>
            </template>

            <template #amount="{ row }">
              <div class="flex flex-col gap-1 text-xs text-gray-600">
                <div>
                  <span class="text-gray-500">应付：</span>
                  <span class="font-medium text-gray-900">
                    {{ formatCurrency(row.payable_amount) }}
                  </span>
                </div>
                <div>
                  <span class="text-gray-500">已付：</span>
                  <span class="text-gray-900">
                    {{ formatCurrency(row.paid_amount) }}
                  </span>
                </div>
              </div>
            </template>

            <template #operation="{ row, size }">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :icon="useRenderIcon('ep:view')"
                :size="size"
                @click="openDetail(row)"
              >
                查看
              </el-button>
              <el-button
                v-if="nextStatusActions(row).length"
                class="reset-margin"
                link
                type="success"
                :icon="useRenderIcon('ep:check')"
                :size="size"
                @click="quickAdvance(row)"
              >
                推进
              </el-button>
            </template>
          </PureTable>
        </template>
      </PureTableBar>
    </el-card>

    <!-- 生成结算单 -->
    <el-dialog
      v-model="generateVisible"
      title="生成结算单"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="generateRules"
        label-width="96px"
      >
        <el-form-item label="卖家组织" prop="seller_org_id">
          <el-select
            v-model="generateForm.seller_org_id"
            clearable
            filterable
            remote
            reserve-keyword
            placeholder="选择组织"
            :remote-method="loadSellerOrgOptions"
            :loading="orgLoading"
          >
            <el-option
              v-for="item in sellerOrgOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="结算周期" prop="period_range">
          <el-date-picker
            v-model="generateForm.period_range"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="generateForm.remark"
            type="textarea"
            :rows="3"
            placeholder="可选，补充说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateVisible = false">取消</el-button>
        <el-button type="primary" :loading="generating" @click="submitGenerate">
          确认生成
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-drawer
      v-model="detailVisible"
      :with-header="false"
      size="60%"
      :destroy-on-close="true"
    >
      <template #default>
        <el-scrollbar v-loading="detailLoading" class="detail-scroll">
          <div class="detail-header">
            <div>
              <div class="text-lg font-medium">
                结算单：{{ currentDetail?.statement_no }}
              </div>
              <div class="text-sm text-gray-500 mt-1">
                结算周期：{{ currentDetail?.period_start }} 至
                {{ currentDetail?.period_end }}
              </div>
            </div>
            <el-button
              v-if="detailStatusActions.length"
              type="primary"
              :icon="useRenderIcon('ep:promotion')"
              @click="showTransitionMenu = true"
            >
              推进状态
            </el-button>
          </div>

          <el-alert
            v-if="currentDetail"
            :title="`当前状态：${currentDetail.status_label}`"
            type="info"
            show-icon
            class="mb-4"
          />

          <el-descriptions
            v-if="currentDetail"
            :column="3"
            border
            size="small"
            label-class-name="w-32"
          >
            <el-descriptions-item label="卖家组织">
              {{ currentDetail.seller_org_name || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="应付金额">
              {{ formatCurrency(currentDetail.payable_amount) }}
            </el-descriptions-item>
            <el-descriptions-item label="已付金额">
              {{ formatCurrency(currentDetail.paid_amount) }}
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              {{ formatCurrency(currentDetail.total_order_amount) }}
            </el-descriptions-item>
            <el-descriptions-item label="退款金额">
              {{ formatCurrency(currentDetail.total_refund_amount) }}
            </el-descriptions-item>
            <el-descriptions-item label="佣金金额">
              {{ formatCurrency(currentDetail.commission_amount) }}
            </el-descriptions-item>
            <el-descriptions-item label="生成时间">
              {{ currentDetail.generated_at || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="确认时间">
              {{ currentDetail.confirmed_at || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="开票时间">
              {{ currentDetail.invoiced_at || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="打款时间">
              {{ currentDetail.paid_at || "-" }}
            </el-descriptions-item>
          </el-descriptions>

          <el-form
            v-if="currentDetail"
            ref="detailFormRef"
            :model="detailForm"
            label-width="96px"
            class="mt-4 detail-form"
          >
            <el-form-item label="备注">
              <el-input
                v-model="detailForm.remark"
                type="textarea"
                :rows="3"
                placeholder="填写备注信息"
              />
            </el-form-item>
            <el-form-item
              v-if="currentDetail.status === 3 || currentDetail.status === 4"
              label="实际打款金额"
            >
              <el-input-number
                v-model="detailForm.paid_amount"
                :precision="2"
                :min="0"
                :max="currentDetail.payable_amount"
              />
              <span class="ml-2 text-xs text-gray-500">默认不超过应付金额</span>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                plain
                :loading="detailUpdating"
                @click="saveDetailRemark"
              >
                保存备注
              </el-button>
            </el-form-item>
          </el-form>

          <el-tabs v-if="currentDetail" class="mt-4">
            <el-tab-pane label="结算明细" name="items">
              <el-table
                :data="currentDetail.items"
                border
                size="small"
                empty-text="暂无明细"
              >
                <el-table-column
                  prop="order_no"
                  label="订单号"
                  min-width="160"
                />
                <el-table-column
                  prop="order_amount"
                  label="订单金额"
                  min-width="120"
                >
                  <template #default="{ row }">
                    {{ formatCurrency(row.order_amount) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="refund_amount"
                  label="退款金额"
                  min-width="120"
                >
                  <template #default="{ row }">
                    {{ formatCurrency(row.refund_amount) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="commission_amount"
                  label="佣金金额"
                  min-width="120"
                >
                  <template #default="{ row }">
                    {{ formatCurrency(row.commission_amount) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="net_amount"
                  label="结算金额"
                  min-width="120"
                >
                  <template #default="{ row }">
                    {{ formatCurrency(row.net_amount) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="发票记录" name="invoices">
              <el-table
                :data="currentDetail.invoices"
                border
                size="small"
                empty-text="暂无发票"
              >
                <el-table-column
                  prop="invoice_no"
                  label="发票号"
                  min-width="140"
                />
                <el-table-column prop="invoice_type" label="类型" width="100" />
                <el-table-column prop="amount" label="金额" min-width="120">
                  <template #default="{ row }">
                    {{ formatCurrency(row.amount) }}
                  </template>
                </el-table-column>
                <el-table-column prop="tax_rate" label="税率" width="90">
                  <template #default="{ row }">
                    {{ row.tax_rate !== null ? `${row.tax_rate}%` : "-" }}
                  </template>
                </el-table-column>
                <el-table-column prop="status_label" label="状态" width="120">
                  <template #default="{ row }">
                    <el-tag size="small" effect="plain">
                      {{ row.status_label || row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="submitted_at"
                  label="提交时间"
                  min-width="160"
                />
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="打款记录" name="payouts">
              <el-table
                :data="currentDetail.payouts"
                border
                size="small"
                empty-text="暂无打款"
              >
                <el-table-column
                  prop="payout_no"
                  label="打款单号"
                  min-width="160"
                />
                <el-table-column prop="amount" label="金额" min-width="120">
                  <template #default="{ row }">
                    {{ formatCurrency(row.amount) }}
                  </template>
                </el-table-column>
                <el-table-column prop="pay_method" label="方式" width="100" />
                <el-table-column prop="status_label" label="状态" width="120">
                  <template #default="{ row }">
                    <el-tag size="small" effect="plain">
                      {{ row.status_label || row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="scheduled_at"
                  label="计划时间"
                  min-width="160"
                />
                <el-table-column
                  prop="paid_at"
                  label="打款时间"
                  min-width="160"
                />
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-scrollbar>
      </template>
    </el-drawer>

    <el-dialog
      v-model="showTransitionMenu"
      title="推进到下一个状态"
      width="420px"
      :close-on-click-modal="false"
    >
      <el-radio-group
        v-model="selectedTargetStatus"
        class="flex flex-col gap-3"
      >
        <el-radio
          v-for="status in detailStatusActions"
          :key="status"
          :label="status"
        >
          {{ STATEMENT_STATUS_MAP[status] }}
        </el-radio>
      </el-radio-group>
      <template #footer>
        <el-button @click="showTransitionMenu = false">取消</el-button>
        <el-button
          type="primary"
          :loading="detailUpdating"
          @click="confirmTransition"
        >
          确认推进
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { ElMessageBox, type FormInstance } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { PureTableBar } from "@/components/RePureTableBar";
import { message } from "@/utils/message";
import { useListPage } from "@/composables/useListPage";
import {
  fetchStatementList,
  getStatementDetail,
  generateStatement,
  updateStatement,
  STATEMENT_STATUS_OPTIONS,
  STATEMENT_STATUS_MAP,
  type StatementListItem,
  type StatementListResult,
  type StatementFilterParams,
  type StatementDetail
} from "@/api/system/settlement/statement";
import {
  fetchOrganizationList,
  type OrganizationListItem
} from "@/api/system/org/organization";

interface FilterForm {
  keyword: string;
  seller_org_id: number | string;
  status: number | string;
  period_range: [string, string] | [];
}

const STATUS_TRANSITIONS: Record<number, number[]> = {
  0: [1, 2],
  1: [2],
  2: [3],
  3: [4],
  4: []
};

const DEFAULT_FILTER: FilterForm = {
  keyword: "",
  seller_org_id: "",
  status: "",
  period_range: []
};

const formRef = ref<FormInstance>();
const tableRef = ref();

const {
  formState: filterForm,
  pagination,
  dataList,
  loading,
  onSearch,
  resetForm,
  handlePageChange,
  handleSizeChange
} = useListPage<
  FilterForm,
  StatementListItem,
  StatementListResult,
  StatementFilterParams
>(
  {
    fetch: params => fetchStatementList(params as StatementFilterParams)
  },
  DEFAULT_FILTER,
  {},
  {
    paramsAdapter: params => {
      const adapted: Record<string, any> = {
        page: params.page,
        page_size: params.page_size,
        keyword: params.keyword || undefined,
        status:
          params.status === "" || params.status === undefined
            ? undefined
            : params.status,
        seller_org_id:
          params.seller_org_id === "" || params.seller_org_id === undefined
            ? undefined
            : params.seller_org_id
      };

      if (
        Array.isArray(params.period_range) &&
        params.period_range.length === 2
      ) {
        adapted.period_start = params.period_range[0];
        adapted.period_end = params.period_range[1];
      }

      return adapted;
    },
    responseAdapter: response => ({
      list: response.list,
      total: response.pagination.total,
      pageSize: response.pagination.pageSize,
      currentPage: response.pagination.currentPage
    })
  }
);

const tableData = computed(() => dataList.value ?? []);

const columns: TableColumnList = [
  { label: "结算单号", prop: "statement_no", minWidth: 180, align: "left" },
  {
    label: "卖家组织",
    prop: "seller_org_name",
    minWidth: 180,
    align: "left"
  },
  {
    label: "结算周期",
    minWidth: 200,
    formatter: (row: StatementListItem) =>
      `${row.period_start} 至 ${row.period_end}`
  },
  {
    label: "金额概览",
    prop: "amount",
    minWidth: 160,
    slot: "amount"
  },
  {
    label: "状态",
    prop: "status",
    width: 120,
    slot: "status"
  },
  {
    label: "生成时间",
    prop: "generated_at",
    minWidth: 160
  },
  {
    label: "操作",
    prop: "operation",
    width: 180,
    fixed: "right",
    slot: "operation"
  }
];

const statusTagType = (status: number) => {
  switch (status) {
    case 4:
      return "success";
    case 2:
    case 3:
      return "warning";
    case 0:
      return "info";
    default:
      return "primary";
  }
};

const formatCurrency = (value: number) =>
  new Intl.NumberFormat("zh-CN", {
    style: "currency",
    currency: "CNY"
  }).format(value ?? 0);

const resetFilters = async () => {
  await resetForm();
  await onSearch();
};

const sellerOrgOptions = ref<Array<{ id: number; name: string }>>([]);
const orgLoading = ref(false);

const loadSellerOrgOptions = async (keyword?: string) => {
  orgLoading.value = true;
  try {
    const res = await fetchOrganizationList({
      page: 1,
      page_size: 20,
      org_type: "seller",
      keyword: keyword?.trim() || undefined
    });
    sellerOrgOptions.value = res.list.map(item => ({
      id: item.id,
      name: item.name
    }));
  } catch (error: any) {
    message(error?.message ?? "加载组织失败", { type: "error" });
  } finally {
    orgLoading.value = false;
  }
};

/* 生成结算单 */
const generateVisible = ref(false);
const generating = ref(false);
const generateFormRef = ref<FormInstance>();
const generateForm = reactive({
  seller_org_id: "" as number | string,
  period_range: [] as [string, string] | [],
  remark: ""
});

const generateRules = {
  seller_org_id: [
    { required: true, message: "请选择卖家组织", trigger: "change" }
  ],
  period_range: [
    {
      required: true,
      message: "请选择结算周期",
      trigger: "change"
    }
  ]
};

const openGenerateDialog = () => {
  generateVisible.value = true;
  if (sellerOrgOptions.value.length === 0) {
    loadSellerOrgOptions();
  }
};

const submitGenerate = async () => {
  const form = generateFormRef.value;
  if (!form) return;
  const valid = await form.validate().catch(() => false);
  if (!valid) return;

  if (!Array.isArray(generateForm.period_range)) return;

  generating.value = true;
  try {
    const payload = {
      seller_org_id: Number(generateForm.seller_org_id),
      period_start: generateForm.period_range[0],
      period_end: generateForm.period_range[1],
      remark: generateForm.remark || undefined
    };
    await generateStatement(payload);
    message("结算单生成成功", { type: "success" });
    generateVisible.value = false;
    generateForm.seller_org_id = "";
    generateForm.period_range = [];
    generateForm.remark = "";
    await onSearch();
  } catch (error: any) {
    message(error?.message ?? "生成结算单失败", { type: "error" });
  } finally {
    generating.value = false;
  }
};

/* 详情 */
const detailVisible = ref(false);
const detailLoading = ref(false);
const detailUpdating = ref(false);
const showTransitionMenu = ref(false);
const selectedTargetStatus = ref<number | null>(null);
const detailFormRef = ref<FormInstance>();
const currentDetail = ref<StatementDetail | null>(null);
const detailForm = reactive({
  remark: "",
  paid_amount: 0
});

const loadDetail = async (id: number) => {
  detailLoading.value = true;
  try {
    const detail = await getStatementDetail(id);
    currentDetail.value = detail;
    detailForm.remark = detail.remark ?? "";
    detailForm.paid_amount = detail.paid_amount ?? 0;
  } catch (error: any) {
    message(error?.message ?? "获取详情失败", { type: "error" });
    detailVisible.value = false;
  } finally {
    detailLoading.value = false;
  }
};

const openDetail = (row: StatementListItem) => {
  detailVisible.value = true;
  loadDetail(row.id);
};

const detailStatusActions = computed<number[]>(() => {
  if (!currentDetail.value) return [];
  const current = currentDetail.value.status ?? 0;
  return STATUS_TRANSITIONS[current] ?? [];
});

const nextStatusActions = (row: StatementListItem): number[] => {
  return STATUS_TRANSITIONS[row.status] ?? [];
};

const quickAdvance = (row: StatementListItem) => {
  openDetail(row);
  showTransitionMenu.value = true;
  const actions = nextStatusActions(row);
  selectedTargetStatus.value = actions[0] ?? null;
};

const saveDetailRemark = async () => {
  if (!currentDetail.value) return;
  detailUpdating.value = true;
  try {
    const payload: Record<string, any> = {
      remark: detailForm.remark
    };
    if (
      (currentDetail.value.status === 3 || currentDetail.value.status === 4) &&
      detailForm.paid_amount !== undefined
    ) {
      payload.paid_amount = detailForm.paid_amount;
    }
    const updated = await updateStatement(currentDetail.value.id, payload);
    currentDetail.value = updated;
    detailForm.remark = updated.remark ?? "";
    detailForm.paid_amount = updated.paid_amount ?? 0;
    message("备注已保存", { type: "success" });
    await onSearch();
  } catch (error: any) {
    message(error?.message ?? "保存失败", { type: "error" });
  } finally {
    detailUpdating.value = false;
  }
};

const confirmTransition = async () => {
  if (!currentDetail.value || selectedTargetStatus.value === null) {
    message("请选择目标状态", { type: "warning" });
    return;
  }
  const target = selectedTargetStatus.value;
  const payload: Record<string, any> = {
    status: target,
    remark: detailForm.remark || undefined
  };
  if (target === 4) {
    if (
      detailForm.paid_amount === undefined ||
      detailForm.paid_amount === null
    ) {
      await ElMessageBox.alert("请先填写实际打款金额", "提示", {
        type: "warning"
      });
      return;
    }
    payload.paid_amount = detailForm.paid_amount;
  }

  detailUpdating.value = true;
  try {
    const updated = await updateStatement(currentDetail.value.id, payload);
    currentDetail.value = updated;
    detailForm.remark = updated.remark ?? "";
    detailForm.paid_amount = updated.paid_amount ?? 0;
    showTransitionMenu.value = false;
    selectedTargetStatus.value = null;
    message("状态已更新", { type: "success" });
    await onSearch();
  } catch (error: any) {
    message(error?.message ?? "推进状态失败", { type: "error" });
  } finally {
    detailUpdating.value = false;
  }
};

watch(
  () => detailVisible.value,
  visible => {
    if (!visible) {
      currentDetail.value = null;
      showTransitionMenu.value = false;
      selectedTargetStatus.value = null;
    }
  }
);

onMounted(async () => {
  await onSearch();
  if (sellerOrgOptions.value.length === 0) {
    loadSellerOrgOptions();
  }
});

watch(
  () => [showTransitionMenu.value, detailStatusActions.value],
  ([visible, actions]) => {
    if (visible && Array.isArray(actions) && actions.length > 0) {
      if (selectedTargetStatus.value === null) {
        selectedTargetStatus.value = actions[0];
      }
    }
    if (!visible) {
      selectedTargetStatus.value = null;
    }
  }
);
</script>

<style scoped>
.settlement-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 12px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.detail-form :deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.detail-scroll {
  padding: 0 16px 24px;
  height: 100%;
}

.detail-scroll :deep(.el-table) {
  margin-top: 12px;
}
</style>
